package tech.yunland.shop.domain.service;

import com.moyuer.bsf.domain.dao.UserDao;
import com.moyuer.bsf.domain.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.ExamDao;
import tech.yunland.shop.domain.dao.ExamDescriptionDao;
import tech.yunland.shop.domain.dao.LessonsDao;
import tech.yunland.shop.domain.dao.ScoreDao;
import tech.yunland.shop.domain.model.Exam;
import tech.yunland.shop.domain.model.Lessons;
import tech.yunland.shop.domain.model.Score;

import java.math.BigInteger;
import java.util.List;

/**
 * Created by v on 17-7-3.
 */
@Service
public class ExamServiceImpl implements ExamService {

    @Autowired
    private LessonsDao lessonsDao;

    @Autowired
    private ExamDao examDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ScoreDao scoreDao;

    @Autowired
    private ExamDescriptionDao examDescriptionDao;

    @Override
    public void save(Exam exam) {
//        for (Exam exam : exams) {
        if (exam.getExamTime() != null) {
            exam.setExamDescription(examDescriptionDao.get(exam.getDesid()));
            exam.setLessons(lessonsDao.get(exam.getLid()));
            examDao.save(exam);
            Lessons lessons = exam.getLessons();
            String hql =
                    "SELECT u\n" +
                            "FROM User u\n" +
                            "WHERE u.id IN (SELECT ul.students.id\n" +
                            "             FROM UserLessons ul\n" +
                            "             WHERE ul.lessons.id = '" + lessons.getId() + "')";
            List<User> users = userDao.find(hql);
            for (User user : users) {
                Score score = new Score();
                score.setStudents(user);
                score.setExam(exam);
                scoreDao.save(score);
            }
        }
//        }
    }

    @Override
    public Integer getSize(String desid) {
        String sql =
                "select count(1) counts\n" +
                        "from exam e where e.examdescription_id = '" + desid + "'";
        int counts = ((BigInteger) examDao.findUniqueBySQL(sql).get("counts")).intValue();
        return counts;
    }

    @Override
    public List<Exam> get(String desid, Integer startIdx, Integer rows) {
        String hql = "from Exam e where e.examDescription.id = '" + desid + "'";
        return examDao.find(hql, startIdx, rows);
    }
}
